package com.example.shop.interceptors;

import com.example.shop.utils.JwtUtil;
import com.example.shop.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * @projectName: travel
 * @package: com.example.travel.interceptors
 * @className: LoginInterceptor
 * @author: Liqian
 * @description: TODO
 * @date: 2024/4/12 18:34
 * @version: 1.0
 */

/*
 * 请求拦截
 * */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            ThreadLocalUtil.set(claims);
            System.out.println("登录状态校验成功");
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            System.out.println("登录状态校验失败");
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
